<?php
/**
 * 权限逻辑层
 * @author Toby.tu 2016-08-30
 */
class PermissionLogic extends My_Model {
	private $login_userid_key = '';
    private $grouptypelist = array('1'=>'admin','2'=>'home');
    public function init(){
        $this->login_userid_key = $this->common->pwd(config_item('login_userid_key').'_current_user_id');
    }
	/**
	 * 判断是否登录
	 * @author Toby.tu 2016-08-30
	 */
	public function is_login($id=0){
	    $user = $this->getLoginUserInfo();
	    if(!empty($user)){
	    	return true;
	    }
	    return false;
	}
	/**
	 * 存入session中
	 * @author Toby.tu 2016-08-30
	 */
	public function setLoginUserInfo($user=array()){
		if(empty($user)) return false;
		$this->load->library('PHPSession');
		$this->phpsession->set($this->login_userid_key,$user);
	    //session_start();
	    //$_SESSION[] = ;
	}
	/**
     * 权限判断
     * @param String $route 控制器和方法
     * 格式：Admin/User/index
     * @param Integer $userid 用户id，为空默认为当前账号
     * @return 是否有权限：yes、no
     * @author Tujt 2015-09-01
     */
    public function checkPermission($route = '', $userid = 0) {
        if (empty($route)) {// 如果为空，则判断当前模块
            //获取当前分组、控制器和方法名
            $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $controller = $this->router->class;
			$method = strtolower($this->router->method);
			$routearr = explode('/'.$controller.'/', $callback.'/');
			$controller = strtolower($controller);
			$routearray = explode('/', $routearr[0]);
			$group = strtolower(array_pop($routearray));
        } else {
        	$route = strtr($route,array('/'=>'.'));
            $routearr = explode('.', $route);
            $group = strtolower($routearr[0]); //分组：前后台
            if (isset($routearr[1]))
                $controller = strtolower($routearr[1]); //控制器
            else
                $controller = '';
            if (isset($routearr[2]))
                $method = strtolower($routearr[2]); //方法名
            else
                $method = '';
        }
        if ($userid > 0) {
            $this->load->model('User_model','UserModel');
            $user = $this->UserModel->getOne(['id'=>$userid]);
            if(0 == $user['status']){
                return 'no';
            }
        } else {
            $user = $this->getLoginUserInfo();
        }
        if ($this->isAdmin($user) == 'yes')
            return 'yes';//超级管理员
        $ispermis = 'no';
        if (isset($user['permis_id']) && !empty($user['permis_id'])) {
            //获取权限id对应的权限列表
            $this->load->model('Permismodule_model','permismodule_model');
            //获取分组对应的权限列表
            $permis_list = $this->permismodule_model->getPermisModuleByGroupId($user['permis_id']);
            //组装权限数组
            $permis_list = $this->getPermisNameByList($permis_list);
            if(isset($permis_list[$group][$controller][$method])){
                return 'yes';
            }
            // //判断是否拥有分组>控制器>方法权限，且必须拥有该模块权限
            // if(isset($permis_list[$group][$controller]['id']) &&
            //         $permis_list[$group][$controller]['id'] > 0){//必须首先拥有控制器权限
            //     if('index' == $method){//首页权限
            //         $ispermis = 'yes';
            //     }else if (isset($permis_list[$group][$controller]['child'][$method])){
            //         $ispermis = 'yes';
            //     }
            // }
        }
        return $ispermis;
    }
    /**
     * 获取当前分组、控制器、方法
     * @author Toby.tu 2016-09-01
     */
    public function getRouter(){
        $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $controller = $this->router->class;
        $method = strtolower($this->router->method);
        $routearr = explode('/'.$controller.'/', $callback.'/');
        $controller = strtolower($controller);
        $routearray = explode('/', $routearr[0]);
        $group = strtolower(array_pop($routearray));
        return array('group'=>$group,'controller'=>$controller,'method'=>$method);
    }
    /**
     * 是否为管理员
     * @param Array $user 账号信息数组
     * 格式：User::find(1)->toArray() 数组格式
     * @return 是否为管理员：yes、no
     * @author Tujt 2015-09-01
     */
    public function isAdmin($user = array()) {
        $isadmin = 'no'; //非管理员
        if (empty($user)) {
            $user = $this->getLoginUserInfo();
        }
        if (1 == $user['is_admin']) {//超级管理员，拥有所有权限
            $isadmin = 'yes'; //是管理员
        }
        return $isadmin;
    }
    /**
     * 获取当前登录用户的信息
     * @author perry 2015-08-26
     */
    public function getLoginUserInfo() {
		$this->load->library('PHPSession');
		$user = $this->phpsession->get($this->login_userid_key);
		if(!empty($user)){
			return $user;
		}
		return array();
        //static $static_session_start;
        //if(1 != $static_session_start){
            //session_start();
        //}
        //$static_session_start = 1;
	    //if(isset($_SESSION[$this->login_userid_key]) && !empty($_SESSION[$this->login_userid_key])){
	        //return $_SESSION[$this->login_userid_key];
	    //}
	    //return 0;
    }

    /**
     * 注销登录
     * @author perry 2015-08-26
     */
    public function destoryLoginUserInfo() {
		$this->load->library('PHPSession');
		$this->phpsession->rm($this->login_userid_key);
		//session_start();
		//if($_SESSION[$this->login_userid_key]){
			//unset($_SESSION[$this->login_userid_key]);
		//}
        //$_SESSION[$this->login_userid_key] = array();
    }
    /**
     * 获取模块权限列表
     * @author Toby.tu 2016-08-31
     */
    public function getPermisModuleList($permis_module=array()){
    	if(empty($permis_module)) return array();
    	$permis_list = array();
    	foreach ($permis_module as $permis) {
    		if($permis['parent_id'] > 0){//二级
    			$permis_list[$permis['parent_id']]['list'][$permis['id']]['info'] = $permis;
    		}else{//一级
    			$permis_list[$permis['id']]['info'] = $permis;
    		}
    	}
    	return $permis_list;
    }
    /**
     * 设置权限组权限时，处理传递的参数值
     * @author Toby.tu 2016-08-31
     */
    public function setPermisList($group_id=0,$permis_module_id=array(),$permis_module=array()){
    	if(empty($group_id) || empty($permis_module_id) || empty($permis_module)){
    		return array();
    	}
    	$params = array();
    	foreach ($permis_module_id as $id) {
    		if(!isset($permis_module[$id])){
    			continue;
    		}
            if(empty($permis_module[$id]['url'])){
                continue;
            }
    		$param = array();
    		$param['permis_id'] = $group_id;
    		$param['name'] = $permis_module[$id]['url'];
    		$params[] = $param;
    	}
    	return $params;
    }
    /**
     * 获取分组对应的权限
     * @author Toby.tu 2016-08-31
     */
    public function getPermisNameByList($permis_list=array()){
        if(empty($permis_list)){
            return array();
        }
        $permislist = array();
        foreach ($permis_list as $id=>$permis) {
            // if($permis['parent_id'] > 0){//二级
            //     $permisname = explode('/',$permis['name']);
            //     $module = strtolower($permisname[0]);
            //     $method = strtolower($permisname[1]);
            //     $permislist[$grouptype][$module]['child'][$method] = $permis['id'];
            // }else{
            //     $permisname = explode('/',$permis['name']);
            //     $module = strtolower($permisname[0]);
            //     $method = strtolower($permisname[1]);
            //     $permislist[$grouptype][$module]['id'] = $permis['id'];
            // }
            $permisname = explode('/',$permis['name']);
            $module = strtolower($permisname[0]);
            $controller = strtolower($permisname[1]);
            $method = strtolower($permisname[2]);
            $permislist[$module][$controller][$method] = $permis['id'];
        }
        return $permislist;
    }
    /**
     * 获取当前用户可以看到的菜单
     * @author Toby.tu 2016-09-02
     */
    public function getMenuInfo(){
        $this->load->model('Menu_model','menu_model');
        $menus = $this->menu_model->getAll();
        //echo $this->db->last_query();die;
        $menu_list = array();
        // $group = 'admin';
        foreach ($menus as $menu) {
            if(1 != $menu['status']){
                continue;//已禁用
            }
            $router = $this->getRouter();
            if('store' == $router['method']){
                $router['method'] = 'create';
            }else if('update' == $router['method']){
                $router['method'] = 'edit';
            }
            if(2 == $menu['type']){
                continue;//不展示菜单
            }
            $url = $router['group'].'/'.$router['controller'].'/'.$router['method'];
            if($url != strtolower($menu['url']) && 1 != $menu['type']){
                continue;//不展示
            }
            if($menu['parent_id'] > 0){
                if('yes' != $this->checkPermission($menu['url'])){
                    continue;
                }
                $menu_list[$menu['parent_id']]['list'][$menu['id']]['info'] = $menu;
            }else{
                $menu_list[$menu['id']]['info'] = $menu;
            }
        }
        if(!empty($menu_list)){
            $menuinfo = array();
            foreach ($menu_list as $key=>$menu) {
                if(!isset($menu['list']) && empty($menu['info']['url'])) continue;
                $menuinfo[$key] = $menu;
            }
            return $menuinfo;
        }
        return array();
    }

    /**
     *
     */
    public function checkMenu(){
        $router = $this->getRouter();
        if('store' == $router['method']){
            $router['method'] = 'create';
        }else if('update' == $router['method']){
            $router['method'] = 'edit';
        }
        $url = $router['group'].'/'.$router['controller'].'/'.$router['method'];
        $menu = $this->getOne(['url'=>$url],'menu');
        if(!empty($menu) && 1 != $menu['type']){
            if(empty($this->router->uri->rsegments[3])){
                return false;
            }
        }
        return true;
    }
}
